// 44min used
#include "kernel/types.h"
#include "user/user.h"

void sieve(int *pipe_fd) {
  int p, q, next_pipe[2];

  if (read(pipe_fd[0], &p, sizeof(int)) == 0) {
    close(pipe_fd[0]);
    return;
  }
  printf("prime %d\n", p);

  pipe(next_pipe);

  if (fork()) {
    close(next_pipe[0]);
    int child_status;
    while (read(pipe_fd[0], &q, sizeof(int))) {
      if (q % p) {
        write(next_pipe[1], &q, sizeof(int));
      }
    }

    close(pipe_fd[0]);
    close(next_pipe[1]);

    wait(&child_status);
  } else {
    close(pipe_fd[0]);
    close(next_pipe[1]);
    sieve(next_pipe);
  }
}

int main(int argc, char *argv[]) {

  int next_pipe[2];
  pipe(next_pipe);

  if (fork()) {
    close(next_pipe[0]);
    int child_status;
    for (int i = 2; i <= 280; ++i) {
      write(next_pipe[1], &i, sizeof(int));
    }

    close(next_pipe[1]);
    wait(&child_status);
  } else {
    close(next_pipe[1]);
    sieve(next_pipe);
  }

  exit(0);
}
